import React,{useState,useEffect,useRef} from 'react'
import { Table, Button,Modal,Switch} from 'antd'
import axios from 'axios'
import { DeleteOutlined,EditOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import UserForm from '../../../components/user-manage/UserForm';
const { confirm } = Modal;
export default function UserList() {
  const [dataSource , setdataSource ] = useState([])
  const [regionList, setregionList] = useState([])
  const [roleList, setroleList] = useState([])
  const [isAddvisible, setisAddvisible] = useState(false)
  const [isUpdatevisible, setisUpdatevisible] = useState(false)
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  const [current, setcurrent] = useState(null)
  const addForm = useRef(null)
  const updateForm = useRef(null)
  const {roleId,region,username} = JSON.parse(localStorage.getItem('token'))
  
  useEffect(() => {
    const roleObj = {
      '1':'superAdmin',
      '2':'admin',
      '3':'editor'
    }
    axios.get('/users?_expand=role').then(res=>{
      const list = res.data
      setdataSource(roleObj[roleId] === 'superAdmin'?list:[
        ...list.filter(item=>item.username === username),
        ...list.filter(item=>item.region === region && roleObj[item.roleId] === 'editor' )
      ])
    })
    axios.get('/regions').then(res=>{
      setregionList(res.data)
    })
    axios.get('/roles').then(res=>{
      setroleList(res.data)
    })
  
    return () => {
      
    }
  }, [roleId,region,username])
  
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters:[
        {
          text:'全球',
          value:'全球'
        },
        ...regionList.map(item=>({
            text:item.title,
            value:item.value
        }))
      ],
      onFilter: (value, item) => {
        if(value === '全球'){
          return item.region === ''
        }
        return item.region === value
      },
      render:(region)=>{
        return<b>{region===''?'全球':region}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render:(role)=>{
        return role?.roleName
      }
    },
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render:(roleState,item)=>{
        return <Switch checked={roleState} onChange={()=>onChange(item)} disabled={item.default} />
      }
    },
    {
      title: '操作',
      render:(item)=>{
        return(
          <div>
            <Button danger shape="circle" icon={<DeleteOutlined />} onClick={()=>confirmMethod(item)} disabled={item.default}/>
            <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={()=>updateMethod(item)} />
          </div>
        )
      }
    },
  ];

  const updateMethod = (item)=>{
    setisUpdatevisible(true)
    // 同步触发
    setTimeout(() => {
      if(item.roleId===1){
        setisUpdateDisabled(true)
      }else{
        setisUpdateDisabled(false)
      }
      updateForm.current.setFieldsValue(item)
    },0);
    setcurrent(item)
  }

  const onChange =(item)=>{
    item.roleState = !item.roleState
    setdataSource([...dataSource])
    axios.patch(`/users/${item.id}`,{
      roleState:item.roleState
    })
  }

  const confirmMethod = (item)=>{
    confirm({
      title: '你确定要删除此权限吗?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const deleteMethod = (item)=>{
    setdataSource(dataSource.filter(data=>data.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }

  const addFormOK = ()=>{
    addForm.current.validateFields().then(value=>{
      setisAddvisible(false)
      addForm.current.resetFields()
      // post到后端，生成id，在设置datasource，方便后面的删除和更新
      axios.post(`/users`,{
        ...value,
        "roleState": true,
        "default": false
      }).then(res=>{
        setdataSource([...dataSource,{...res.data,role:roleList.filter(item=>item.id===value.roleId)[0]}])
      })
    }).catch(err=>{
      console.log(err)
    })
  }
  
  const updateFormOK = ()=>{
    setisUpdatevisible(false)
    updateForm.current.validateFields().then(value=>{
      setdataSource(dataSource.map(item=>{
        if(item.id === current.id){
          return{
            ...item,
            ...value,
            role:roleList.filter(item=>item.id===value.roleId)[0]
          }
        }
        return item
      }))
      setisUpdateDisabled(!isUpdateDisabled)
      axios.patch(`/users/${current.id}`,value)
    })
  }

  return (
    <div>
      <Button type="primary" onClick={()=>setisAddvisible(true)}>新增用户</Button>
      <Table dataSource={dataSource} columns={columns} rowKey={(item)=>item.id} />

    <Modal
      visible={isAddvisible}
      title="新增用户"
      okText="确定"
      cancelText="取消"
      onCancel={()=>{setisAddvisible(false)}}
      onOk={() => {
        addFormOK()
      }}
    >
      <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
    </Modal>
    <Modal
      visible={isUpdatevisible}
      title="更新用户"
      okText="更新"
      cancelText="取消"
      onCancel={()=>{
        setisUpdatevisible(false)
        setisUpdateDisabled(!isUpdateDisabled)
      }}
      onOk={() => {
        updateFormOK()
      }}
    >
      <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled} isUpate={true}></UserForm>
    </Modal>

    </div>
  )
}
